/**
 * DocumentView 组件 - 显示和交互式操作生成的项目文档
 * 
 * 这个组件负责渲染生成的Markdown文档，并提供以下交互功能：
 * - 复制文档内容到剪贴板
 * - 导出文档为Markdown文件
 * - 通过指令修改现有文档
 * - 缩放功能，调整文档显示大小
 * - AI聊天功能，可以针对文档内容提问
 * 
 * 文档内容使用ReactMarkdown渲染，支持语法高亮和表格等扩展功能。
 * 包含错误处理逻辑，当文档内容无法正确渲染时提供备用UI。
 */
"use client";

import { Button } from "./ui/button";
import { useLanguage } from "~/lib/LanguageContext";
import ReactMarkdown from "react-markdown";
import { useState, useRef, useEffect } from "react";
import { ZoomControl } from "./zoom-control";
import AIChatStream from './ai-chat-stream';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
import remarkGfm from 'remark-gfm';
import Prism from 'prismjs';
import 'prismjs/themes/prism-tomorrow.css';
import 'prismjs/components/prism-markdown';
import 'prismjs/components/prism-bash';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-typescript';
import 'prismjs/components/prism-jsx';
import 'prismjs/components/prism-tsx';
import 'prismjs/components/prism-python';
import 'prismjs/components/prism-java';
import 'prismjs/components/prism-c';
import 'prismjs/components/prism-cpp';
import 'prismjs/components/prism-csharp';
import 'prismjs/components/prism-go';
import 'prismjs/components/prism-rust';
import 'prismjs/components/prism-json';
import 'prismjs/components/prism-yaml';

interface DocumentViewProps {
  document: string;
  onCopy: () => void;
  onExport: () => void;
  onModify: (instructions: string) => void;
  repoUrl?: string; // 添加仓库URL属性
}

export default function DocumentView({
  document,
  onCopy,
  onExport,
  onModify,
  repoUrl,
}: DocumentViewProps) {
  const { t } = useLanguage();
  const [modifyInstructions, setModifyInstructions] = useState("");
  const [showModifyInput, setShowModifyInput] = useState(false);
  const [zoom, setZoom] = useState(100);
  const documentRef = useRef<HTMLDivElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [showAiChat, setShowAiChat] = useState(false);
  const [selectedText, setSelectedText] = useState("");
  const [renderError, setRenderError] = useState(false);

  const handleZoomChange = (newZoom: number) => {
    setZoom(newZoom);
    
    if (documentRef.current) {
      const scale = newZoom / 100;
      documentRef.current.style.transform = `scale(${scale})`;
      documentRef.current.style.transformOrigin = 'top left';
    }
  };

  // 处理文本选择事件
  useEffect(() => {
    const handleSelection = () => {
      const selection = window.getSelection();
      if (selection && selection.toString()) {
        setSelectedText(selection.toString());
      }
    };
    
    if (typeof window !== 'undefined') {
      window.document.addEventListener('mouseup', handleSelection);
      return () => {
        window.document.removeEventListener('mouseup', handleSelection);
      };
    }
    return () => {};
  }, []);

  // 处理代码块的语法高亮
  useEffect(() => {
    try {
      Prism.highlightAll();
    } catch (error) {
      console.error("Syntax highlighting error:", error);
    }
  }, [document]);

  // 验证文档是否为有效的Markdown
  useEffect(() => {
    setRenderError(false);
    if (!document || document.trim() === '') {
      setRenderError(true);
    }
  }, [document]);

  const handleSubmitModify = () => {
    if (modifyInstructions.trim() === "") return;
    onModify(modifyInstructions);
    setModifyInstructions("");
    setShowModifyInput(false);
  };

  // 提供渲染错误时的回退界面
  const renderFallbackContent = () => (
    <div className="w-full p-8 text-center">
      <div className="mb-6 text-red-500 dark:text-red-400">
        <svg xmlns="http://www.w3.org/2000/svg" className="inline-block h-12 w-12" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
        </svg>
      </div>
      <h3 className="mb-2 text-xl font-bold text-gray-800 dark:text-gray-200">文档渲染出现问题</h3>
      <p className="mb-6 text-gray-600 dark:text-gray-400">无法显示文档内容。您可以尝试以下操作：</p>
      <div className="flex justify-center gap-4">
        <Button
          onClick={() => onModify("Please regenerate the document with improved formatting.")}
          className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
        >
          重新生成文档
        </Button>
        <Button
          onClick={onCopy}
          className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
        >
          复制原始内容
        </Button>
      </div>
    </div>
  );

  return (
    <div className="flex w-full flex-col items-center">
      <div className="mb-5 flex w-full max-w-4xl justify-between items-center">
        <div className="flex gap-2">
          <Button
            onClick={() => setShowModifyInput(!showModifyInput)}
            className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
          >
            {showModifyInput ? t("cancel") : t("modify")}
          </Button>
          
          <Button
            onClick={() => setShowAiChat(!showAiChat)}
            className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
          >
            {showAiChat ? t("close") : t("ai_chat")}
          </Button>
        </div>
        
        <div className="flex-1 flex justify-center">
          <ZoomControl onZoomChange={handleZoomChange} initialZoom={100} />
        </div>
        
        <div className="flex gap-2">
          <Button
            onClick={onCopy}
            className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
          >
            {t("copy")}
          </Button>
          <Button
            onClick={onExport}
            className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
          >
            {t("export")}
          </Button>
        </div>
      </div>

      {showModifyInput && (
        <div className="mb-5 w-full max-w-4xl">
          <textarea
            value={modifyInstructions}
            onChange={(e) => setModifyInstructions(e.target.value)}
            placeholder={t("modifyDocumentPlaceholder")}
            className="w-full rounded-md border-[3px] border-black p-4 shadow-[4px_4px_0_0_#000000] focus:outline-none dark:border-gray-700 dark:bg-gray-800 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f]"
            rows={4}
          />
          <div className="mt-2 flex justify-end">
            <Button
              onClick={handleSubmitModify}
              disabled={modifyInstructions.trim() === ""}
              className="border-[3px] border-black bg-blue-400 px-4 py-2 text-black shadow-[4px_4px_0_0_#000000] transition-transform hover:-translate-x-0.5 hover:-translate-y-0.5 hover:bg-blue-300 disabled:opacity-50 dark:border-gray-700 dark:bg-blue-600 dark:text-white dark:shadow-[4px_4px_0_0_#1f1f1f] dark:hover:bg-blue-500"
            >
              {t("submit")}
            </Button>
          </div>
        </div>
      )}

      <div className="flex w-full max-w-4xl">
        <div 
          className={`${
            showAiChat ? 'w-1/2 pr-4' : 'w-full'
          } transition-all`}
        >
          <div 
            className="border-[3px] border-black rounded-md shadow-[4px_4px_0_0_#000000] dark:border-gray-700 dark:shadow-[4px_4px_0_0_#1f1f1f] bg-white dark:bg-gray-800 overflow-hidden"
          >
            <div 
              ref={scrollContainerRef}
              className="markdown-body h-[calc(100vh-200px)] min-h-[400px] overflow-auto p-6 scroll-smooth"
              style={{ 
                overflowY: 'auto',
                overflowX: 'auto',
                scrollBehavior: 'smooth'
              }}
            >
              {renderError ? renderFallbackContent() : (
                <div 
                  ref={documentRef} 
                  className="transition-transform duration-300 prose prose-slate dark:prose-invert max-w-none"
                  style={{ transformOrigin: 'top left' }}
                >
                  <ReactMarkdown
                    remarkPlugins={[remarkGfm]}
                    rehypePlugins={[rehypeRaw, rehypeSanitize]}
                    skipHtml={false}
                    unwrapDisallowed={false}
                    components={{
                      // 自定义代码块渲染
                      code({ node, inline, className, children, ...props }: any) {
                        const match = /language-(\w+)/.exec(className || '');
                        return !inline && match ? (
                          <pre className={`language-${match[1]} rounded-md`}>
                            <code className={`language-${match[1]}`} {...props}>
                              {String(children).replace(/\n$/, '')}
                            </code>
                          </pre>
                        ) : (
                          <code className={className} {...props}>
                            {children}
                          </code>
                        );
                      },
                      // 自定义标题样式
                      h1: ({ node, ...props }: any) => (
                        <h1 className="text-2xl font-bold mt-6 mb-4 pb-2 border-b" {...props} />
                      ),
                      h2: ({ node, ...props }: any) => (
                        <h2 className="text-xl font-bold mt-5 mb-3 pb-1 border-b" {...props} />
                      ),
                      h3: ({ node, ...props }: any) => (
                        <h3 className="text-lg font-bold mt-4 mb-2" {...props} />
                      ),
                      // 自定义列表样式
                      ul: ({ node, ...props }: any) => (
                        <ul className="list-disc pl-6 my-3" {...props} />
                      ),
                      ol: ({ node, ...props }: any) => (
                        <ol className="list-decimal pl-6 my-3" {...props} />
                      ),
                      // 自定义链接样式
                      a: ({ node, ...props }: any) => (
                        <a className="text-blue-500 hover:underline" {...props} />
                      ),
                      // 自定义表格样式
                      table: ({ node, ...props }: any) => (
                        <div className="overflow-x-auto my-4">
                          <table className="min-w-full border-collapse border border-gray-300 dark:border-gray-700" {...props} />
                        </div>
                      ),
                      thead: ({ node, ...props }: any) => (
                        <thead className="bg-gray-100 dark:bg-gray-800" {...props} />
                      ),
                      th: ({ node, ...props }: any) => (
                        <th className="border border-gray-300 dark:border-gray-700 px-4 py-2 text-left" {...props} />
                      ),
                      td: ({ node, ...props }: any) => (
                        <td className="border border-gray-300 dark:border-gray-700 px-4 py-2" {...props} />
                      ),
                      // 自定义引用样式
                      blockquote: ({ node, ...props }: any) => (
                        <blockquote className="border-l-4 border-gray-300 dark:border-gray-700 pl-4 py-1 my-3 italic text-gray-700 dark:text-gray-300" {...props} />
                      ),
                      // 自定义图片样式
                      img: ({ node, ...props }: any) => (
                        <img className="max-w-full h-auto my-4 rounded-md" {...props} />
                      ),
                      // 自定义段落样式
                      p: ({ node, ...props }: any) => (
                        <p className="my-3" {...props} />
                      ),
                    }}
                  >
                    {document || "文档加载失败。请尝试重新生成或检查内容格式。"}
                  </ReactMarkdown>
                </div>
              )}
            </div>
          </div>
        </div>

        {showAiChat && (
          <div className="w-1/2 pl-4 border-l border-gray-200 dark:border-gray-700 h-[calc(100vh-200px)] min-h-[400px]">
            <AIChatStream 
              repoUrl={repoUrl}
              selectedDocument={selectedText || document}
              onClose={() => setShowAiChat(false)}
            />
          </div>
        )}
      </div>
    </div>
  );
} 